package com.kws.merchant.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.domain.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.domain.po.DevicePo;
import com.kws.merchant.domain.po.RemarkPo;
import com.kws.merchant.domain.po.StatusCheck;
import com.kws.merchant.domain.vo.GoodsRemarkVo;
import com.kws.merchant.domain.vo.RemarkVo;
import com.kws.merchant.domain.vo.DeviceVo;
import com.kws.merchant.mapper.DeviceMapper;
import com.kws.merchant.service.*;
import com.kws.merchant.util.FileUtil;
import com.kws.system.api.domain.SysUser;
import com.kws.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;


/**
 * 商品-设备(Device)表服务实现类
 *
 * @author yxy
 * @since 2024-10-22 11:03:38
 */
@Service("deviceService")
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {

    @Resource
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceRemarkService deviceRemarkService;
    @Autowired
    private DeviceImgService deviceImgService;
    @Autowired
    private GoodsViewService goodsViewService;
    @Autowired
    private SpecificationService specificationService;
    @Autowired
    private OrderService orderService;
    @Autowired
    @Lazy
    private MerchantService merchantService;
    @Value("${minio.ENDPOINT}")
    private String minioUrl;

    /**
     * 分页查询列表
     *
     * @param devicePo
     * @return
     */
    @Override
    public Page<Device> pageList(DevicePo devicePo) {
        Integer pageSize = devicePo.getPageSize();
        Integer totalPage = devicePo.getTotalPage();
        String name = devicePo.getName();//姓名
        String type = devicePo.getType();//类型
        String status = devicePo.getStatus();//状态
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        //查询是否为商家
        boolean flag = sysUser.getCompanyId()!=null;
        String sql = " ";
        if (flag) {
            sql+=" and a.merchant_id="+sysUser.getCompanyId();
        }
        if (!StringUtils.isEmpty(name)) {
            sql += " and a.name like '%" + name+"%'";
        }
        if (!StringUtils.isEmpty(type)) {
            sql += " and a.type=" + type;
        }
        if (!StringUtils.isEmpty(status)) {
            sql += " and a.status=" + status;
        }
        int total = deviceMapper.countToTal(sql);
        int sizeNum = (pageSize - 1) * totalPage;//计算分页
        //查询签名数据
        List<Device> records = deviceMapper.getRecords(sql, sizeNum, totalPage);
        records.forEach(x->{
            x.setImg(FileUtil.fixFileName()+x.getImg());
        });
        Page<Device> page = new Page<>();
        page.setRecords(records);
        page.setTotal(total);
        page.setCurrent(pageSize);
        page.setPages((total + totalPage - 1) / totalPage);
        page.setSize(totalPage);
        return page;
    }

    /**
     * 设备上下架
     *
     * @param statusCheck
     * @return
     */
    @Override
    public boolean updateStatus(StatusCheck statusCheck) {
        Device device = this.getById(statusCheck.getId());
        if (ObjectUtils.isEmpty(device)) {
            throw new RuntimeException("设备不存在");
        }
        if (device.getStatus()==2){
            throw new RuntimeException("设备审核中，不能操作！！");
        }
        //上架需要审核
        if (statusCheck.getType() == 0) {
            device.setStatus(2);
        } else if (statusCheck.getType() == 1) {
            device.setStatus(1);
        } else {
            throw new RuntimeException("设备审核中，无法上下架");
        }
        return this.updateById(device);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id
     * @return
     */
    @Override
    public DeviceVo detailById(Long id) {
        DeviceVo deviceVo = new DeviceVo();
        Device device = deviceMapper.detailById(id);
        if (ObjectUtils.isEmpty(device)) {
            throw new RuntimeException("没有该设备信息");
        }
        //查询设备规格
        List <Specification> specifications=specificationService.listByGoodsId(id);
        //颜色
        String color = specifications.stream().map(x -> x.getColor()).collect(Collectors.joining(","));
        device.setSpecifications(specifications);
        device.setImg(FileUtil.fixFileName() + device.getImg());
        //根据设备id查询多张图片
        List<String> imgArr = deviceImgService.listByDeviceId(id).stream().map(x -> x.getDeviceImg()).collect(Collectors.toList());
        device.setImgArr(imgArr);
        deviceVo.setDevice(device);
        //根据设备id查询评论--不分页压力过大，单独调用
        /*List<DeviceRemark> remarkByDeviceId = deviceRemarkService.getRemarkByDeviceId(id);
        deviceVo.setRemarkList(remarkByDeviceId);*/
        //根据设备计算评分，规则为平均分
        GoodsRemarkVo goodsRemarkVo = deviceRemarkService.scoreAvg(id);
        deviceVo.setGoodsRemarkVo(goodsRemarkVo);
        deviceVo.setSuggestedPrice(device.getPrice());//建议价格
        deviceVo.setColors(color);//颜色
        deviceVo.setQuantity(device.getInventory());//数量
        //统计订单销售数量
        Integer salesVolume=orderService.countByGoodsId(id);
        deviceVo.setSalesVolume(salesVolume);//销量
        return deviceVo;
    }

    /**
     * 根据设备编码获取设备信息
     *
     * @param code
     * @return
     */
    @Override
    public Device getByCode(String code) {
        return this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getCode, code));
    }

    /**
     * 新增设备
     *
     * @param device
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addDevice(Device device) {
        UUID uuid = UUID.randomUUID();
        device.setCode("SB"+uuid);
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        device.setMerchantId(companyId);
        device.setImg(FileUtil.subFileName(device.getImg()));
        //新增设备默认下架
        device.setStatus(1);
        //默认设备为待审核状态
        device.setAuditStatus("0");
        this.save(device);
        List<String> imgArr = device.getImgArr();
        Long deviceId = device.getId();
        deviceImgService.saveImgs(deviceId, imgArr);
        return true;
    }

    /**
     * 设备评论
     *
     * @return
     */
    @Override
    public boolean deviceRemark(RemarkPo remarkPo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        DeviceRemark deviceRemark = new DeviceRemark();
        deviceRemark.setDeviceId(remarkPo.getId());
        deviceRemark.setRemark(remarkPo.getContent());
        deviceRemark.setObserver(sysUser.getUserId());
        deviceRemark.setObserverPhone(sysUser.getPhonenumber());
        deviceRemark.setScore(remarkPo.getScore());
        deviceRemark.setTag(remarkPo.getTag());
        deviceRemark.setPid(remarkPo.getPid());
        deviceRemark.setRemarkType("1");
        List<String> remarkImg = remarkPo.getRemarkImg();
        String imgStr = org.apache.commons.lang3.StringUtils.join(remarkImg, ",");
        deviceRemark.setRemarkImg(imgStr);
        deviceRemark.setOrderId(remarkPo.getOrderId());
        return deviceRemarkService.save(deviceRemark);
    }

    /**
     * 修改设备数据
     *
     * @param device
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDevice(Device device) {
        if (device.getStatus() != 1) {
            throw new RuntimeException("商品未下架，不可修改");
        }
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        device.setMerchantId(companyId);
        device.setImg(FileUtil.subFileName(device.getImg()));
        device.setStatus(1);
        //修改设备
        this.updateById(device);
        //存储设备图片
        List<String> imgArr = device.getImgArr();
        Long serveId = device.getId();
        deviceImgService.saveImgs(serveId, imgArr);
        return true;
    }

    /**
     * 删除设备
     *
     * @param id
     * @return
     */
    @Override
    public Object delete(Long id) {
        Device device = this.getById(id);
        if (device.getStatus() != 1) {
            throw new RuntimeException("商品未正常下架，无法删除");
        }
        return device;
    }

    /**
     * 撤销审核
     *
     * @param id
     * @return
     */
    @Override
    public boolean repealCheck(Long id) {
        Device device = this.getById(id);
        device.setStatus(1);
        return this.updateById(device);
    }

    /**
     * 删除设备-可删除多个
     * @param idList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object removeByIdList(List<Long> idList) {
        idList.forEach(x->{
            //删除设备图片
        deviceImgService.remove(Wrappers.<DeviceImg>lambdaQuery().eq(DeviceImg::getDeviceId,x));
        });
        //删除设备
        this.removeByIds(idList);
        return true;
    }

    /**
     * 商家设备列表
     * @return
     */
    @Override
    public List<Device> listByMerchant() {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        return this.list(Wrappers.<Device>lambdaQuery().eq(Device::getMerchantId,companyId));
    }


}
